﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using LinqToLfsWorld.Extensions;

namespace LinqToLfsWorld.Queries
{
	/// <summary>
	/// Queries LfsWorld for information on registered game teams.
	/// </summary>
	public class TeamQuery : LfsWorldQuery<Team>
	{

		/// <summary>
		/// Initializes a new instance of the <see cref="TeamQuery"/> class.
		/// </summary>
		/// <param name="context">The context.</param>
		public TeamQuery(LfsWorldContext context)
			: base(context)
		{
		}

		/// <summary>
		/// Gets the URL used to query LfsWorld.
		/// </summary>
		/// <returns></returns>
		protected override string GetUrl()
		{
			return LfsHelper.GetPubstatUrlBase(PubstatResponseType.Xml, this, "teams");
		}

		/// <summary>
		/// Gets the entities given LfsWorld response XML
		/// </summary>
		/// <param name="responseData">The response data.</param>
		/// <returns>A collection of Host entities</returns>
		protected override IEnumerable<Team> ProcessResponse(string responseData)
		{
			XDocument doc = XDocument.Parse(responseData);

			foreach (var node in doc.Descendants("entry"))
			{
				Team team = new Team();

				team.Id = Convert.ToInt32(node.Element("tid").Value);
				team.Name = node.Element("team").Value;
				team.Tag = node.Element("tag").Value;
				team.Country = node.Element("country").Value;
				team.Url = node.Element("url").Value;
				team.Flags = (TeamFlags)(Convert.ToInt32(node.Element("bits").Value));
				team.TeamInfo = HttpUtility.UrlDecode(node.Element("info").Value);

				XElement racersElement = node.Element("members_array");
				team.Members = (from m in racersElement.Elements() select m.Value.StripLfsColours()).ToArray();

				yield return team;
			}

			yield break;
		}

	}
}
